package cn.kgc.spring07.proxy;

import cn.kgc.spring07.mapper.UserMapper;
import cn.kgc.spring07.mapper.impl.UserMapperImpl;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author: mosin
 * @version: v1.0  2022/12/5
 * Cglib的代理是基于父子类关系的代理
 */
public class CglibProxy {

    public static void main(String[] args) {

        UserMapperImpl userMapper = new UserMapperImpl();

        Enhancer enhancer = new Enhancer();

        //设置生成的代理类的父类
        enhancer.setSuperclass(UserMapperImpl.class);
        //设置代理类的增强的功能
        MethodInterceptor methodInterceptor = new MethodInterceptor() {

            // Method method      Object[] objects
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

                System.out.println("---------log日志------------");

                Object invoke = method.invoke(userMapper, objects);

                System.out.println("---------log日志------------");
                return invoke;
            }
        };
        enhancer.setCallback(methodInterceptor);
        // 创建代理对象   代理对象是 UserMapperImpl的子类
        UserMapperImpl o = (UserMapperImpl) enhancer.create();
        Integer delete = o.delete(1);
        System.out.println("delete = " + delete);


    }
}
